package lz.student.student.controller;

import lz.student.student.dto.ScoreDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Controller
@RequestMapping("student")
public class StudentController {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @GetMapping("login")
    public String login() {
        return "/student/login";
    }

    @RequestMapping("query")
    public String query(String idCard, String name, Model model) {

        if (idCard == null || idCard.isEmpty()) {
            model.addAttribute("errMsg", "身份证号码不能为空");
            return "/student/login";
        }
        if (name == null || name.isEmpty()) {
            model.addAttribute("errMsg", "姓名不能为空");
            return "/student/login";
        }
        String sql = "select id,id_card as idCard,name,score,evaluate from score where id_card = ? and name = ? ";
        List<ScoreDto> scoreDtos = jdbcTemplate.query(sql, new RowMapper<ScoreDto>() {
                    @Override
                    public ScoreDto mapRow(ResultSet rs, int rowNum) throws SQLException {
                        ScoreDto scoreDto = new ScoreDto();
                        scoreDto.setId(rs.getLong("id"));
                        scoreDto.setIdCard(rs.getString("idCard"));
                        scoreDto.setName(rs.getString("name"));
                        scoreDto.setScore(rs.getInt("score"));
                        scoreDto.setEvaluate(rs.getString("evaluate"));
                        return scoreDto;
                    }
                }, idCard, name
        );
        if (scoreDtos.isEmpty()) {
            model.addAttribute("errMsg", "查询不到此人的成绩");
            return "/student/login";
        }

        model.addAttribute("score", scoreDtos.get(0));
        return "/student/query";
    }



}
